<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Crypt;

use DB;

class AdminController extends Controller
{
    //add
    public function add()
    {

    	return view('admin.admin.add');
    }

    public function insert(Request $request)
    {
    	// dd($request -> all());
    	// 验证表单
    	$this -> validate($request,[
    		'username' => 'required|unique:admin',
    		'password' => 'required|max:20|min:6',
    		'email' => 'required|email|unique:admin',
    		'phone' => 'required|max:11|min:11'


    		],[
    		'username.required' => '用户名不能为空',
    		'username.unique' => '用户名已存在',
    		'password.required' => '密码不能为空',
    		'password.max' => '密码最大20位',
    		'password.min' => '密码最少6位',
    		'email.required' => '邮箱不能为空',
    		'email.email' => '邮箱格式不正确',
    		'email.unique' => '邮箱地址已存在',
    		'phone.required' => '手机号不能为空',
    		'phone.max' => '手机号必须是11位',
    		'phone.min' => '手机号必须是11位'
    		

    	]);

    	//处理好所有数据
    	$data = $request -> except('_token','repassword');
    	// dd($data);

    	//加密密码
    	$data['password'] = Crypt::encrypt($data['password']);
    	// dd($data);

    	// //解密示例
    	// // $a = "eyJpdiI6IktcL0Q4M3YyakJNclIyTlIzN041eXBRPT0iLCJ2YWx1ZSI6IkFoWG5nbjhMS3NBRURHbDJqMGtURHc9PSIsIm1hYyI6IjM5NTEzZGJlYmYwZWQ0NmI3ZDMwNTAxM2FlOWJjOTlkNzU1Mjk4MDdkYzViOTE0YzJiMDU0OGNkYWRjMzU3YjQifQ==";

    	// // $A = Crypt::decrypt($a);
    	// // dd($A);
    	
    	$data['remember_token'] = str_random(70);
    	$time = date('Y-m-d H:i:s');
    	$data['created_at'] = $time;
    	// $data['updated_at'] = $time;
    	// dd($data);

    	//添加数据
    	$res = DB::table('admin') -> insert($data);
    	// dd($res);
    	
    	if($res)
    	{
    		// return ('添加成功');
    		return redirect('/admin/admin/index') -> with(['info' => '添加成功']);
    	}else
    	{
    		// return ('添加失败');
    		return redirect('/admin/admin/add') -> with(['error' => '添加失败']);
    	}

    }

    //index
    public function index(Request $request)
    {

    	// dd($request -> all());
    	//查询数据库
    	
    	$data = DB::table('admin') 
    		-> where(function($query) use ($request){
    			$query -> where('email', 'like', '%'.$request -> input('keyword').'%');
    		})
    		-> get();

    		// dd($data);
 
    	return view('/admin/admin/index',['data' => $data, 'request' => $request -> all() ]) ;
    }


    //编辑
    public function edit($id)
    {

    	// dd($id);
    	//查询数据库
    	$data = DB::table('admin') -> where('id',$id) -> first();
    	if(!$data)
    	{
    		return redirect('/admin/index/index');
    	}
    	// dd($data);
    	return view('admin.admin.edit',['data' => $data] );
    }

    //更新
    public function update(Request $request)
    {
    	// dd($request -> all());

    	$this -> validate($request,[
    		'username' => 'unique:admin',
    		'password' => 'max:20|min:6',
    		'email' => 'email|unique:admin',
    		'phone' => 'max:11|min:11'
    		],[
    		
    		'username.unique' => '用户名已存在',
    		'password.max' => '密码最大20位',
    		'password.min' => '密码最少6位',
    		'email.email' => '邮箱格式不正确',
    		'email.unique' => '邮箱地址已存在',
    		'phone.max' => '手机号必须是11位',
    		'phone.min' => '手机号必须是11位'

    	]);

    	$data = $request -> except('_token','id');
    	$prerogative = DB::table('admin')->select('prerogative') -> where('id',$request -> input('id') ) -> first();
    	if(!$data)
    	{
    		return redirect('/admin/index/index');
    	}
    	// dd($prerogative -> prerogative);
    	// 
    	//判断是否更新
    	if(empty($request -> input('username')))
    	{
    		unset($data['username']);
    	}

    	if(empty($request -> input('email')))
    	{
    		unset($data['email']);
    	}

    	if(empty($request -> input('phone')))
    	{
    		unset($data['phone']);
    	}
    	if(empty($request -> input('password')))
    	{
    		unset($data['password']);
    	}else
    	{	
	    	//加密密码
	    	$data['password'] = Crypt::encrypt($data['password']);
    	}

    	if($request -> input('prerogative') == $prerogative -> prerogative)
    	{
    		unset($data['prerogative']);
    	}

    	if(empty($data))
    	{
    		return back();
    	}else
    	{
    		$time = date('Y-m-d H:i:s');
    		$data['updated_at'] = $time;
    	}


    	// dd($data);

    	//执行更新
    	$res = DB::table('admin') -> where('id',$request -> input('id')) -> update($data);

    	//判断
    	if($res)
    	{
    		return  back() -> with(['info' => '更新成功']);
    	}else
    	{
    		return back() -> with(['error' => '更新失败']);
    	}
    }

    //delete
    public function delete($id)
    {
    	
    	$oldImg = DB::table('admin') -> where('id', $id) -> first() -> img;
    	//判断是否为管理员
    	if($id == 999999)
    	{
    		return redirect('/admin/admin/index');
    	}

    	$res = DB::table('admin') -> delete($id);

    	//判断
    	if($res)
    	{
    		if(file_exists('.').$oldImg != '/uploads/admin/default.png')
	    		{
	    			if(file_exists('.'.$oldImg))
		    		{
		    			unlink('.'.$oldImg);
		    		}
	    		}
    		return redirect('/admin/admin/index') -> with(['info' => '删除成功']);
    	}else
    	{
    		return back() -> with(['error' => '删除失败']);
    	}
    }

    //ajaxUpdate
    public function ajaxUpdate(Request $request)
    {
    	// dd($request -> all());
    	$id = trim($request -> input('id'));

    	//根据ID查询数据
    	$data = DB::table('admin') -> where('id', $id) -> first();
    	// dd($data -> status);
    	//判断
    	if($data -> status == '0')
    	{
    		$res = DB::table('admin') -> where('id', $id) -> update(['status' => '1']);
    		if($res)
    		{
    			return response() -> json(0);
    		}else
    		{
    			return response() -> json(1);
    		}
    	}else
    	{
    		$res = DB::table('admin') -> where('id', $id) -> update(['status' => '0']);
    		if($res)
    		{
    			return response() -> json(2);
    		}else
    		{
    			return response() -> json(3);
    		}
    	}

    }

    //edit_info
    public function edit_info($id)
    {
    	//查询数据库
    	$data = DB::table('admin') -> where('id',$id) -> first();
    	if(!$data)
    	{
    		return redirect('/admin/index/index');
    	}
    	return view('admin.admin.edit_info',['data' => $data ]);
    }

    //更新管理员个人中心
    public function update_info(Request $request)
    {
    	$id = $request -> input('id');
    	$oldImg = DB::table('admin') -> where('id', $id) -> first() -> img;
    	// dd($oldImg);
    	// dd($request -> all());
    	$this -> validate($request,[
    		'username' => 'unique:admin',
    		'password' => 'max:20|min:6',
    		'email' => 'email|unique:admin',
    		'phone' => 'max:11|min:11'
    		],[
    		
    		'username.unique' => '用户名已存在',
    		'password.max' => '密码最大20位',
    		'password.min' => '密码最少6位',
    		'email.email' => '邮箱格式不正确',
    		'email.unique' => '邮箱地址已存在',
    		'phone.max' => '手机号必须是11位',
    		'phone.min' => '手机号必须是11位'

    	]);
    	$data = $request -> except('_token','id');
    	$password = DB::table('admin') -> select('password') -> where('id',$request -> input('id')) -> first();
    	$password = Crypt::decrypt($password -> password);
    	if($data['password'] == $password)
    	{
    		return back() -> with(['error' => '您的密码与上次相同，修改失败!']);
    	}
    	
    	//判断是否更新
    	if(empty($request -> input('username')))
    	{
    		unset($data['username']);
    	}

    	if(empty($request -> input('email')))
    	{
    		unset($data['email']);
    	}

    	if(empty($request -> input('phone')))
    	{
    		unset($data['phone']);
    	}
    	if(empty($request -> input('nickname')))
    	{
    		unset($data['nickname']);
    	}
    	if(empty($request -> input('password')))
    	{
    		unset($data['password']);
    	}else
    	{	
	    	//加密密码
	    	$data['password'] = Crypt::encrypt($data['password']);
    	}

    	if(empty($data))
    	{
    		return back();
    	}else
    	{
    		$time = date('Y-m-d H:i:s');
    		$data['created_at'] = $time;
    	}
    	//判断图片
    	if($request -> hasFile('img')) 
    	{
    		if($request -> file('img') -> isValid())
    		{

    			//获取扩展名称
	    		$suffix = $request -> file('img') -> getClientOriginalExtension();
	    		// dd($suffix);
	    		//判断文件类型
	    		//允许的文件扩展名
				$allowed_types = array('jpg', 'gif', 'png');
				//转化成小写
				$suffix = strtolower($suffix);
				//判断是否在被允许的扩展名里
				if(!in_array($suffix, $allowed_types)){
				 return back() -> with(['error' => '文件类型不符合']);
				}

	    		//随机名称
	    		$fileName = time().mt_rand(100000,999999).'.'.$suffix;

	    		$request -> file('img') -> move('./uploads/admin/', $fileName);

	    		//处理 img 字段
	    		$data['img'] = '/uploads/admin/'.$fileName;
                dd($oldImg);
	    		if($oldImg != '/uploads/admin/default.png')
	    		{
                    // dd('图片不相同');
	    			if(file_exists('.'.$oldImg))
		    		{
		    			unlink('.'.$oldImg);
		    		}
	    		}
    		}
    		
    	}
    	dd($data);
    	//执行更新
    	$res = DB::table('admin') -> where('id',$request -> input('id')) -> update($data);

    	//判断
    	if($res)
    	{
    		return back() -> with(['info' => '更新成功','data' => $data ]);
    	}else
    	{
    		return back() -> with(['error' => '更新失败']);
    	}
    }
}
